package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@RestController
@RequestMapping("/mobile/setmeal")
@Slf4j
public class SetMealController {

    @Reference
    private SetMealService setMealService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 查询套餐
     * @return
     */
    @GetMapping("/getSetmeal")
    public Result getSetmeal(){
        try(Jedis jedis = jedisPool.getResource()) {
            if (jedisPool != null && jedis!=null ) {
                // redis可用,获取一个Jedis对象

                // 检查redis中是否有学科列表
                String courseListStr = jedis.get("getSetmeal");
                if (courseListStr == null) {
                    // 无可用列表
                    log.debug("redis中，没有套餐列表获取一个放入redis");
                    // 调用Service
                    List<Setmeal> setmeals = setMealService.findAll();
                    // 放入redis的必须是JSON字符串（使用fastjson,把List转换为JSON字符串）
                    jedis.set("getSetmeal", JSON.toJSONString(setmeals));
                    jedis.expire("getSetmeal",60*60*24);
                    // 响应JSON
                    return new Result(true, MessageConst.GET_SETMEAL_LIST_SUCCESS, setmeals);
                } else {
                    log.debug("redis中有数据，JSON字符串变为JSON对象，返回客户端");
                    // 有可用列表，把JSON字符串变为JSON对象
                    Object jsonObject = JSON.parse(courseListStr);
                    return new Result(true, MessageConst.GET_SETMEAL_LIST_SUCCESS, jsonObject);

                }
            } else {
                // 调用Service
                List<Setmeal> setmeals = setMealService.findAll();
                // 响应JSON
                return new Result(true, MessageConst.GET_SETMEAL_LIST_SUCCESS, setmeals);
            }
        }
       /* //rpc调用查询所有套餐
        List<Setmeal> setmeals = setMealService.findAll();
        return new Result(true, MessageConst.GET_SETMEAL_LIST_SUCCESS,setmeals);*/
    }
    @GetMapping("/findById")
    public Result findById(Integer id){
        //rpc调用查询数据
        Setmeal setmeal = setMealService.findById(id);
        //返回
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
    }
}
